<?php

namespace App\Http\Controllers\Home;


use App\Models\Home\User;
use App\Models\Home\UserInfo;
use App\Models\RTresult;
use App\Models\TempEmail;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Validator;
use App\Models\TempPhone;
use App\Tool\SMS\SendTemplateSMS;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;


class ForgetController extends Controller
{
    //忘记密码的视图
    public function index(){

        return view('home.forgetpass');
    }

    //发送忘记密码的手机短信验证码
    public function sendreset(Request $request)
    {
        $rt_result = new RTresult();
        //获取返回的数据对象
        //获取填写的手机号
        $phone = $request->phone;
        //查询手机号是否已注册
        $result = DB::table('users')->where('phone', '=', $phone)->first();
        if (!$result) {
            $rt_result->status = 1;
            $rt_result->message = '账号不存在';
            return $rt_result->toJson();
        }

        //定义随机因子
        $charset = '1234567890';
        $phoneMsg = new SendTemplateSMS();
        //随机得到随机因子
        $code = '';
        $len = strlen($charset);
        for ($i = 0; $i < 4; $i++) {
            $code .= $charset{mt_rand(0, strlen($len))};
        }

        $rt_result = $phoneMsg->send($phone, array($code, 60), 1);

        if ($rt_result->status == 0) {
            //获取tmp_phone表模型
            $phone_temp = new TempPhone();
            $phone_temp->phone = $phone;
            $phone_temp->code = $code;
            $phone_temp->deadline = time() + 5 * 60;
            $phone_temp->save();
        }
        return $rt_result->toJson();
    }

    //忘记密码通过邮箱发送验证码
    public function sendCode(Request $request)
    {
        $rt_result = new RTresult();

        //获取填写的邮箱
        $email = $request->user;
        //查询邮箱是否已注册
        $result = DB::table('user_infos')->where('email', $email)->first();
        if (!$result) {
            $rt_result->status = 1;
            $rt_result->message = '账号不存在';
            return $rt_result->toJson();
        }

        //如果已注册，生成6位数字随机码发送过去
        $str = md5(random_int(0, time()));
        //获取字符串的长度
        $length = strlen($str) - 1;
        //字符串截取长度
        $count = 6;
        //字符串截取开始位置
        $start = rand(0, $length - $count);
        //随机截取字符串，取其中的一部分字符串
        $code = substr($str, $start, $count);

        //将随机码通过邮件发送到用户邮箱
        Mail::raw('您的验证码为'.$code.'有效期5分钟',
            function ($message) use ($email) {
                $message->to($email)->subject('osdoc密码重置验证码');
            });

        //发送成功后
        $rt_result->status = true;
        $rt_result->message = '邮件发送成功，请查收';
        //将验证码存入数据库以备验证
        $email_temp = new TempEmail();
        $email_temp->email = $email;
        $email_temp->code = $code;
        $email_temp->deadline = time() + 5 * 60;
        $email_temp->save();
        return $rt_result->toJson();
    }

    //重置密码的视图
    public function new_password(Request $request)
    {
        if ($request->isMethod('post')) {

            $roles = ['phone' => 'required',
                'code' => 'required',
                ];

            $msg = ['required' => ':attribute为必填项',
                'captcha' => ':attribute不正确'];

            $chinese = ['phone' => '手机号',
                'code' => '验证码',

            ];
            //进行格式验证
            $validator = Validator::make($request->all(), $roles, $msg, $chinese);

            if ($validator->fails()) {
                return redirect()->back()->withErrors($validator);
            }

        }
        $phone_temp = new TempPhone();

        $code = $phone_temp::get()->where('phone', '=', $request->phone)->last();

        if ($request->code != $code->code) {

            return view('home.forgetpass')->with("验证码错误");
        }
//        dump($request->toArray());
        //获取上一个页面上的值
        $data['phone'] = $request->phone;

        //将手机号传递到视图里面
        return view('/home/new_password',$data);
    }

    //忘记密码的重置密码视图   按钮
    public function new_login(Request $request){

//       dd($request->toArray());
        $rt_result = new RTresult();
       if ($request->new_password != $request->new_confirm){
           $rt_result->status = 1;
           $rt_result->message = "两次输入的密码不相同";
           return $rt_result->toJson();
        } else {
            //将注册信息存入数据库
            $res = DB::table('users')->where('phone', $request->phone)
                ->update([
                    'password' => Hash::make($request->new_password),
                ]);
            if ($res) {
                return redirect('/login');
            } else {
                return back()->with('fails', '重置密码失败');
            }

        }
    }


}
